#!/usr/bin/env python3
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 08:45:30
# @LastEditTime: 2025-03-14 08:45:35
# @Description: 阿里云容器服务ACK监控模块
###

import os
import json
import logging
from typing import Dict, List
from aliyunsdkcs.request.v20151215 import DescribeClustersRequest
from ..core import AliyunMonitorBase

class ACKMonitor(AliyunMonitorBase):
    """ACK集群监控"""
    
    def __init__(self, config: Dict):
        super().__init__(config)
        self.namespace = "acs_k8s"
        
    def list_clusters(self) -> List[Dict]:
        """获取ACK集群列表"""
        try:
            request = DescribeClustersRequest.DescribeClustersRequest()
            response = self.client.do_action_with_exception(request)
            return json.loads(response)
        except Exception as e:
            logging.error(f"获取ACK集群列表失败: {e}")
            return []
            
    def setup_cluster_monitoring(self, cluster_id: str, cluster_name: str):
        """设置集群监控
        
        Args:
            cluster_id: 集群ID
            cluster_name: 集群名称
        """
        dimensions = [{"clusterId": cluster_id}]
        
        # 节点CPU使用率告警
        self.create_alarm_rule(
            rule_name=f"{cluster_name}-节点CPU使用率告警",
            namespace=self.namespace,
            metric_name="node_cpu_utilization",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['node_cpu']),
            contact_groups=self.config['contact_groups']
        )
        
        # 节点内存使用率告警
        self.create_alarm_rule(
            rule_name=f"{cluster_name}-节点内存使用率告警",
            namespace=self.namespace,
            metric_name="node_memory_utilization",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['node_memory']),
            contact_groups=self.config['contact_groups']
        )
        
        # Pod CPU使用率告警
        self.create_alarm_rule(
            rule_name=f"{cluster_name}-Pod CPU使用率告警",
            namespace=self.namespace,
            metric_name="pod_cpu_utilization",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['pod_cpu']),
            contact_groups=self.config['contact_groups']
        )
        
        # Pod内存使用率告警
        self.create_alarm_rule(
            rule_name=f"{cluster_name}-Pod内存使用率告警",
            namespace=self.namespace,
            metric_name="pod_memory_utilization",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['pod_memory']),
            contact_groups=self.config['contact_groups']
        )
        
        # 节点就绪状态告警
        self.create_alarm_rule(
            rule_name=f"{cluster_name}-节点就绪状态告警",
            namespace=self.namespace,
            metric_name="node_ready_status",
            dimensions=dimensions,
            threshold=1,  # 1表示就绪
            contact_groups=self.config['contact_groups']
        )
        
    def setup_namespace_monitoring(self, cluster_id: str, namespace: str):
        """设置命名空间级别的监控
        
        Args:
            cluster_id: 集群ID
            namespace: 命名空间名称
        """
        dimensions = [
            {"clusterId": cluster_id},
            {"namespace": namespace}
        ]
        
        # 命名空间Pod数量告警
        self.create_alarm_rule(
            rule_name=f"{namespace}-Pod数量告警",
            namespace=self.namespace,
            metric_name="namespace_pod_count",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['namespace_pod_count']),
            contact_groups=self.config['contact_groups']
        )
        
    def get_cluster_metrics(self, cluster_id: str) -> Dict:
        """获取集群的监控指标
        
        Args:
            cluster_id: 集群ID
        """
        dimensions = [{"clusterId": cluster_id}]
        metrics = {}
        
        # 节点CPU使用率
        metrics['node_cpu'] = self.get_metric_data(
            namespace=self.namespace,
            metric_name="node_cpu_utilization",
            dimensions=dimensions
        )
        
        # 节点内存使用率
        metrics['node_memory'] = self.get_metric_data(
            namespace=self.namespace,
            metric_name="node_memory_utilization",
            dimensions=dimensions
        )
        
        # Pod资源使用情况
        metrics['pod_resources'] = self.get_metric_data(
            namespace=self.namespace,
            metric_name="pod_cpu_utilization",
            dimensions=dimensions
        )
        
        return metrics
        
    def monitor_all_clusters(self):
        """监控所有ACK集群"""
        clusters = self.list_clusters()
        for cluster in clusters:
            cluster_id = cluster['cluster_id']
            cluster_name = cluster.get('name', cluster_id)
            
            # 设置集群级别监控
            self.setup_cluster_monitoring(cluster_id, cluster_name)
            
            # 设置默认命名空间监控
            for namespace in ['default', 'kube-system']:
                self.setup_namespace_monitoring(cluster_id, namespace)
                
            logging.info(f"已设置集群监控: {cluster_name}")

# 使用示例
if __name__ == "__main__":
    # 配置示例
    config = {
        "access_key": "your_access_key",
        "secret_key": "your_secret_key",
        "region": "cn-hangzhou",
        "thresholds": {
            "node_cpu": 80,
            "node_memory": 85,
            "pod_cpu": 80,
            "pod_memory": 85,
            "namespace_pod_count": 100
        },
        "contact_groups": ["default"],
        "notification": {
            "dingtalk": {
                "enabled": True,
                "webhook": "your_webhook_url",
                "secret": "your_secret"
            },
            "lark": {
                "enabled": True,
                "webhook": "your_webhook_url"
            }
        }
    }
    
    monitor = ACKMonitor(config)
    
    # 监控所有集群
    monitor.monitor_all_clusters()
    
    # 获取特定集群的指标
    metrics = monitor.get_cluster_metrics("your_cluster_id")
    print(json.dumps(metrics, indent=2))
